#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char *ssid = "MiHome";
const char *password = "ftwc1982";
const char *mqtt_server = "h3253k9765.oicp.vip";
const char *mqttUser = "lu";
const char *mqttPassWd = "5891381";
char mqttID[20];
const int port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastTime = 0;
int i = 0;
void callback(char *topic, byte *payload, unsigned int length)
{
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (int i = 0; i < length; i++)
    {
        Serial.print((char)payload[i]);
    }
    Serial.println();
}
void reconnect()
{
    while (!client.connected())
    {
        Serial.print("Attempting MQTT connection...");
        if (client.connect(mqttID, mqttUser, mqttPassWd))
        {
            Serial.println("connected");
            subScribe();
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            delay(5000);
        }
    }
}

void subScribe()
{
    client.subscribe("POT/Switch");
    client.subscribe("POT/Set");
    client.subscribe("POT/OTA");
}
void initMQTT()
{
    uint8_t macAddr[6];

    WiFi.macAddress(macAddr);
    sprintf(mqttID, "Computer-%X%X", macAddr[4], macAddr[5]);
    client.setServer(mqtt_server, port);
    client.setCallback(callback);
    reconnect();
}
void setup()
{
    Serial.begin(115200);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    initMQTT();
}
void loop()
{
    if (!client.connected())
    {
        reconnect();
    }
    client.loop();
    char msg[20];
    if (millis() - lastTime >= 2000)
    {
        lastTime = millis();
        sprintf(msg, "test%03d", i++);
        Serial.printf("T[test]:test%03d\n", i);
        client.publish("test", msg);
    }
}
